# -*- coding: utf-8 -*-

# === 利用者（ユーザー）の管理用モデル
# パスワードなどの認証に関連する機能はAuthLogicプラグインによって供給される
class User < ActiveRecord::Base
  acts_as_authentic

  validates :nick_name, :uniqueness => true, :presence => true

  has_one :profile, :dependent => :destroy
  has_one :setting, :dependent => :destroy
  has_many :articles, :dependent => :destroy,
                       :conditions => "deleted_flag = 0",
                       :order => "created_at DESC"
  has_many :invites, :dependent => :destroy,
                       :conditions => "status = 'inviting'",
                       :order => "created_at DESC"
  has_many :friend_requests, :dependent => :destroy,
                              :foreign_key => "to_user_id",
                              :order => "id DESC"
  has_and_belongs_to_many :roles

  has_many :friends_from, :foreign_key => 'friend_from_id', :class_name => 'Friend'
  has_many :friends_to,   :foreign_key => 'friend_to_id',   :class_name => 'Friend'
  has_many :friends,          :through => :friends_from, :source => :friend_to
  has_many :friends_referred, :through => :friends_to,   :source => :friend_from

  # 自分が送信したメッセージの取得用
  has_many :my_messages, :foreign_key => "from_user_id", :class_name => "Message"

  # 所有するメッセージオブジェクトのリスト（全件）
  has_many :message_recipients, :dependent => :destroy, :conditions => "delete_flag = 0"
  has_many :messages, :through => :message_recipients, :order => "created_at DESC"

  # 所有するメッセージオブジェクトのリスト（未読のみ）
  has_many :unread_message_recipients,
            :dependent => :destroy,
            :conditions => "delete_flag = 0 AND read_flag = 0",
            :class_name => "MessageRecipient"
  has_many :unread_messages, 
            :through => :unread_message_recipients,
            :source => :message,
            :order => "created_at DESC"
  
  has_many :message_rules, :dependent => :destroy, :order => "id"
  has_many :message_folders, :dependent => :destroy, :order => "name"

  # === 新しくフレンド登録を行う
  def make_friend(friend_to, opt = {})
    raise "invalid argument friend_to. expected 'User' model instance." unless friend_to.is_a?(User)
    return false if self.friends.include?(friend_to)
    opt = {:both_direction => true}.merge(opt)

    ActiveRecord::Base.transaction do
      Friend.create(:friend_from => self, :friend_to => friend_to)
      if opt[:both_direction]
        Friend.create(:friend_from => friend_to, :friend_to => self) unless friend_to.friends.include?(self)
      end
    end
    return true
  end

  # === 指定されたフレンドの削除を行う
  def remove_friend(friend_to)
    raise "invalid argument friend_to. expected 'User' model instance." unless friend_to.is_a?(User)
    return false unless self.friends.include?(friend_to)

    Friend.where(:friend_from_id => self.id, :friend_to_id => friend_to.id).first.delete
  end

  # === 指定されたユーザーが自身のフレンドか判定する
  def friend?(user)
    if self.friends.include?(user)
      return true
    else
      return false
    end
  end

  # === 自身が管理者ロールを持っていれば真を返す
  def admin?
    admin_role = Role.where(:name => "admin").first
    if self.roles.include?(admin_role)
      return true
    else
      return false
    end
  end
end
